<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<%@taglib uri="/WEB-INF/page-base.tld" prefix="w" %>
<%String path = request.getContextPath(); %>
<w:define bind="#moneyOff_classid" id="classid1"/>
<script>
    function loadclasstreeok(){
        $("#classtree1").combotree("setValue","<%=classid1%>");
    }
</script>
<style>
    .showtable{
        width: 302px; min-height: 25px; line-height: 25px; text-align: center; border-collapse: collapse;border:1px solid #e8e8e8;
    }
    .showtable tr th{
        border:1px solid #e8e8e8;
    }
    .showtable tr td{
        border:1px solid #e8e8e8;
    }
    .showtable tr:hover{
        cursor:pointer;
    }
    .tr_odd{
        background-color: orange;
    }
    .tr_even{
        background-color: aqua;
    }
    .mouse_color{
        background-color: green;
    }
    .btn {
        text-decoration: none;
        background-color: #00A4F2;
        color: #fff;
        padding: 5px 20px;
        border-radius: 5px;
    }

    .btn:hover {
        background-color: #00ADFF;
    }

    .ui-btn {
        padding: 15px;
    }

    .newbtna {
        color: red;
        text-decoration: none;
    }

    .inpradio {
        margin-top: 0;
    }

    .datainp {
        width: 173px;
        height: 30px !important;
        border: 1px #A5D2EC solid;
    }

    .wicon {
        background-image: url(
        "");
        background-repeat: no-repeat;
        background-position: right center;
    }

    #errormsg {
        position: fixed;
        width: 200px;
        height: 50px;
        line-height: 50px;
        padding: 1px 5px;
        text-align: center;
        background-color: #00A4F2;
        opacity: 0.5;
        color: #fff;
        left: 50%;
        margin-left: -50px;
        top: 50%;
        border-radius: 20px;
    }

    .datagrid-cell-c2-fullname {
        width: 202px
    }

    .datagrid-cell-c2-productcode {
        width: auto
    }
</style>
<form id="giftform" method="post" action="/marketing/FullGiftsPromotionPage@chooseMoneyList.page">
    <div id="errormsg" style="display: none;"></div>
    <div class="headT">
        <span></span>
        <label>活动定义</label>
    </div>
    <div class="ui-formContent">
        <p>
            <w:hidden bind="bean.id" name="promotionid"/>
            <w:hidden bind="bean.start_time"/>
            <w:hidden bind="bean.end_time"/>
            <label style="width:130px;text-align:right">推广平台：</label>
            <w:radio name="platform" bind="bean.platform" value="0" text="全平台"/>
            <w:radio name="platform" bind="bean.platform" value="1" text="PC端"/>
            <w:radio name="platform" bind="bean.platform" value="2" text="微商城"/>
            <font class="red">*</font>
            <label style="width:130px;text-align:right">活动时间：</label>
            <input class="datainp wicon" id="giftsEditInpstart" name="starttime" value="" type="text" placeholder="请选择"
                   readonly>到
            <input class="datainp wicon" id="giftsEditinpend" name="endtime" value="" type="text" placeholder="请选择"
                   readonly>
            <font class="red">*</font>
        </p>
        <p>
            <label style="width:130px;text-align:right">活动标题：</label>
            <input value="<w:write bind="bean.name" />" name="name" style="width:742px" maxlength="40" styleClass="easyui-validatebox" autocomplete="off" />
            <font class="red">*</font>
        </p>
        <p>
            <label style="width:130px;text-align:right">活动描述：</label>
            <input value="<w:write bind="bean.description" />" name="description" style="width:742px;" maxlength="30" styleClass="easyui-validatebox" autocomplete="off" />
        </p>
        <p>
            <label style="width:130px;text-align:right">排序：</label>
            <input value="<w:write bind="bean.sort_value" />" name="sort_value" style="width:100px" onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}" maxlength="8" styleClass="easyui-validatebox" autocomplete="off" />
        </p>
        <p>
            <label style="width:130px;text-align:right">活动专区描述：</label>
            <input value="<w:write bind="bean.district_description"/>" name="district_description" style="width:731px"
                   maxlength="16" styleClass="easyui-validatebox" autocomplete="off"/>
        </p>
    </div>
    <div class="headT">
        <span></span>
        <label>规则限制</label>
    </div>
    <div class="ui-formContent fullgi" style="position: relative;">
        <div id="productPopup" style="width:800px;">
            <p id="select">
                <label style="width:130px;text-align:right">活动规则：</label>
                <label class="radioButton"><input id="me" name="bean2" checked="checked" class="inpradio" type="radio"
                                                  value="0"/>满额送</label>
                <label class="radioButton"><input id="ml" name="bean2" type="radio" class="inpradio"
                                                  value="1"/>满数量送</label>
                <font class="red">*</font>
            </p>
            <div id="producttab" style="outline: 0;display: none;position: absolute; top: 0;left: 0; z-index: 100000;">
                <table cellpadding="0" cellspacing="0">
                    <tr>
                        <td valign="top" style="padding-top:6px;background-color: #effcfe;">
                            <div style="width:300px;border:1px solid #ddd;height:26px;line-height:26px;background:#fff">
                                <input id="giftLike" style="display:inline-block;border:0px;margin:0px;width:230px;height:20px;float: left;">
                                <a href="javascript:;" style="display:inline-block;float:left;height:26px;background:#F3F3F4;width:40px;color:#666666;text-align:center;font-size:18px;" onclick="hotquerypro();">
                                    <i class="fa fa-search"></i>
                                </a>
                                <%--<button class="close" href="javascript" style="width: 25px;background-color: #fff;">x</button>--%>
                                <a href="javascript:;" class="close"><img style="width: 12.7px;margin-left: 8px;margin-bottom: 2px;" src="<%=path %>/platform/images/close.png"></a>
                            </div>
                            <table class="showtable" id="tab">
                                <thead>
                                <tr>
                                    <th style="width: 150px;">商品名称</th>
                                    <th style="width: 150px;">商品编号</th>
                                </tr>
                                </thead>
                                <tbody id="giftList">

                                </tbody>

                            </table>
                            <div style="text-align: center;padding: 5px 0;">
                                <a href="javascript:void(0)" style="text-decoration: none;color: #fff;padding: 2px;border: 1px solid #1C84C6;border-radius: 5px;background-color: #1C84C6;" id="shang" onclick="shang()">上一页</a>
                                <a href="javascript:void(0)" style="text-decoration: none;color: #fff;padding: 2px;border: 1px solid #1C84C6;border-radius: 5px;background-color: #1C84C6;" id="xia" onclick="xia()">下一页</a>
                            </div>
                        </td>
                    </tr>
                </table>
            </div>
            <div id="full">
                   <w:define id="bean_items" bind="bean.items"/>
                   <w:switch>
                       <w:case bind="#bean_items == null">
                            <div class="full_content">
                                <p class="_full" style="margin-left: 170px;">
                                    <a class="left_add" href="#" style=" color: red;text-decoration: none;" onclick="full_left_add(this)">[+]</a>
                                    满<input name="money_tag" onblur="inputcheck(this);" maxlength='7' autocomplete="off" value="<w:write bind='#item.min_money'/>" data-options="required:true" style="width:100px;margin: 0 5px;"/> 元
                                    送<input name="fulldelivery" onblur="inputcheck2(this);" maxlength='7' autocomplete="off" value="<w:write bind='#gift.unit'/>" data-options="required:true" style="width:100px;margin: 0 5px;"/> 件
                                    <input  name="productinput" autocomplete="off" class="productinput" value="<w:write bind='#gift.productid'/>" type="text" onclick="fullgifts(this);" style="width: 150px;" readonly/>
                                    <a href="#" style=" color: red;text-decoration: none;" onclick="full_right_add(this)">[+]</a>
                                </p>
                            </div>
                       </w:case>
                       <w:case bind="#bean_items.size > 0">
                           <w:iterate id="item" bind="bean.items" indexId="item_index">
                              <div class="full_content">
                                    <p class="_full" style="margin-left: 170px;">
                                    <w:isTrue bind="#item_index==0">
                                        <a class="left_add" href="#" style=" color: red;text-decoration: none;" onclick="full_left_add(this)">[+]</a>
                                    </w:isTrue>
                                    <w:isTrue bind="#item_index!=0">
                                        <a style='padding: 0 5px;' href='javascript:;' class='newbtna' onclick='fulldelone(this)'>[-]</a>
                                    </w:isTrue>

                                    <w:iterate id="gift" bind="#item.gifts" indexId="gift_index">
                                        <w:switch>
                                            <w:case bind="#gift_index== 0">
                                                满 <input name="money_tag" onblur="inputcheck(this);" maxlength='7' autocomplete="off" value="<w:write bind='#item.min_money'/>" data-options="required:true" style="width:100px;margin: 0 5px;" /> 元
                                                送 <input name="fulldelivery" onblur="inputcheck2(this);" maxlength='7' autocomplete="off" value="<w:write bind='#gift.unit'/>" data-options="required:true" style="width:100px;margin: 0 5px;" /> 件
                                                 <input name="productinput" class="productinput" value="<w:write bind='#gift.name'/>" product_id = "<w:write bind='#gift.productid'/>" type="text" onclick="fullgifts(this);" style="width: 150px;" readonly />
                                                <a href="#" style=" color: red;text-decoration: none;" onclick="full_right_add(this)">[+]</a>
                                            </w:case>

                                            <w:else>
                                                <p class='full_list' style='margin-left: 340px;'>
                                                    <i style='font-style: normal;margin-left: 5px;'>送</i>
                                                    <input name="fulldelivery" onblur="inputcheck2(this);" maxlength='7' autocomplete="off" value="<w:write bind='#gift.unit'/>" data-options="required:true" style="width:100px;margin: 0 5px;"><i style='font-style: normal;margin-left: 4px;margin-right: -1px;'>件</i>
                                                    <input name="productinput" autocomplete="off" class="productinput" value="<w:write bind='#gift.name'/>" product_id = "<w:write bind='#gift.productid'/>"  type="text" onclick="fullgifts(this);" style="width: 150px;" readonly />
                                                    <a href='javascript:;' class='newbtna' onclick='fulldeltwo(this)'>[-]</a>
                                                </p>
                                            </w:else>
                                        </w:switch>
                                    </w:iterate>
                                    </p>
                               </div>
                           </w:iterate>
                       </w:case>
                   </w:switch>
            </div>

            <div id="buy">
                    <w:define id="bean_itemsnum" bind="bean.itemsnum"/>
                    <w:switch>
                        <w:case bind="#bean_itemsnum == null">
                            <div class="buy_content">
                                <p style="margin-left: 170px;">
                                    <a href="#" style=" color: red;text-decoration: none;" onclick="buy_left_add(this)">[+]</a>
                                    买<input name="buysend" onblur="inputcheck(this);" maxlength='7' autocomplete="off" value="" data-options="required:true" style="width:100px;margin: 0 5px;">件
                                    送<input name="productunit" onblur="inputcheck2(this);" maxlength='7' autocomplete="off" value="" data-options="required:true" style="width:100px;margin: 0 5px;">件
                                    <input type="text" name="productgive" style="width: 150px;margin: 0 5px;" class="productgive"
                                       onclick="fullgifts(this)" readonly>
                                    <a href="#" style=" color: red;text-decoration: none;" onclick="buy_right_add(this)">[+]</a>
                                </p>
                            </div>
                        </w:case>
                        <w:case bind="#bean_itemsnum.size > 0 ">
                            <w:iterate id="item" bind="bean.itemsnum" indexId="item_index">
                                <div class="buy_content">
                                    <p class="_buy" style="margin-left: 170px;">
                                    <w:isTrue bind="#item_index==0">
                                        <a class="left_add" href="#" style=" color: red;text-decoration: none;" onclick="buy_left_add(this)">[+]</a>
                                    </w:isTrue>
                                    <w:isTrue bind="#item_index!=0">
                                        <a style='padding: 0 5px;' href='javascript:;' class='newbtna' onclick='buydelone(this)'>[-]</a>
                                    </w:isTrue>

                                    <w:iterate id="gift" bind="#item.gifts" indexId="gift_index">
                                        <w:switch>
                                            <w:case bind="#gift_index== 0">
                                                买<input name="buysend" onblur="inputcheck(this);" maxlength='7' autocomplete="off" value="<w:write bind='#item.min_number'/>" data-options="required:true" style="width:100px;margin: 0 5px;" > 件
                                                送<input name="productunit" onblur="inputcheck2(this);" maxlength='7' autocomplete="off" value="<w:write bind='#gift.unit'/>" data-options="required:true" style="width:100px;margin: 0 5px;" > 件
                                                <input name="productgive" class="productinput" value="<w:write bind='#gift.name'/>" product_id = "<w:write bind='#gift.productid'/>" type="text" onclick="fullgifts(this);" style="width: 150px;" readonly>

                                                <a href="#" style=" color: red;text-decoration: none;" onclick="buy_right_add(this)">[+]</a>
                                            </w:case>
                                            <w:else>
                                                <p class='buy_list' style='margin-left: 340px;'>
                                                    <i style='font-style: normal;margin-left: 1px;'>送</i><input name="productunit" onblur="inputcheck2(this);" maxlength='7' value="<w:write bind='#gift.unit'/>" data-options="required:true" style="width:100px;margin: 0 5px;"><i style='font-style: normal;'>件</i>
                                                    <input name="productgive" autocomplete="off" class="productinput" value="<w:write bind='#gift.name'/>" type="text" onclick="fullgifts(this);" product_id = "<w:write bind='#gift.productid'/>" style="width: 150px;" readonly/>
                                                    <a href='javascript:;' class='newbtna' onclick='buydeltwo(this)'>[-]</a>
                                                </p>
                                            </w:else>
                                        </w:switch>
                                    </w:iterate>
                                    </p>
                                </div>
                            </w:iterate>
                        </w:case>
                    </w:switch>
                </div>
            </div>
        </div>

        <div style="border-top: 1px solid #D1D0EA;"></div>

        <div class="ui-formContent">
        <p>
            <label style="width:130px;text-align:right">参与次数：</label>
            <input styleClass="easyui-validatebox" value="<w:write bind="bean.time" />" name="time" style="width:100px" onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"  autocomplete="off" />次
        </p>
        </div>

        <div style="border-top: 1px solid #D1D0EA;"></div>
        <p>
            <label style="width:130px;text-align:right;float: left;">客户范围：</label>
            <select name="controlsales" id="controlsales"
                    style="width:386px;height:200px;border:1px solid #DDDDDD;margin-left: 9px;" multiple="multiple">
                <w:iterate id="info" bind="#controlsales">
                    <option value="{'type':'<w:write bind="#info.type"/>','val':'<w:write bind="#info.val"/>','text':'<w:write bind="#info.text"/>'}">
                        <w:write bind="#info.text"/></option>
                </w:iterate>
            </select>
        </p>
        <div style="margin-top:8px;margin-left: 149px;">
            <a href="javascript:void(0);" class="ui_btn marginR8" onclick="addControlsales()">新增控销</a>
            <a href="javascript:void(0);" class="ui_btn marginR8" onclick="delControlsales()">删除控销</a>
        </div>
    </div>

    <div class="headT">
        <span></span>
        <label>参与方式</label>
    </div>
    <div class="ui-formContent" id="pro_class_set">
        <p style="margin-left: 55px;">
            <input type="hidden" value="<w:write bind="bean.product_type"/>" name="product_type_val">
            <label class="radiocolor"><input name="bean4" id="qc" type="radio" class="inpradio" value="0">全场商品</label>
            <label class="radiocolor"><input name="bean4" id="bf" type="radio" class="inpradio" value="2">部分商品参加</label>
            <label class="radiocolor"><input name="bean4" id="zd" type="radio" class="inpradio" value="3">指定类目</label>
        </p>

        <p id="puctfl">
            <label title="商品分类" style="width:130px;text-align:right">商品分类：</label>
            <select id="classtree1" name="bean.classid1" class="easyui-combotree" style="width:250px;height:28px;"
                    data-options="url:'<%=path %>/products/ProductClassPage@loadClassTree2.page',onLoadSuccess:loadclasstreeok"></select>
        </p>
    </div>


    <div style="width: 100%;  text-align: center; position: absolute;z-index: 10000;bottom:0;"
         class="ui-buttonBar ui-btn">
        <input type="submit" value="完成"/>
    </div>

    <div class="easyui-panel ui-toolBar" border="false" id="selectpro" data-options="doSize:false">
        <table cellpadding="0" cellspacing="0" style="margin-top:5px">
            <tr>
                <td width="70" align="right">商品名称：</td>
                <td><w:text bind="bean.pname" maxlength="50" style="width:120px;height:22px;"/></td>
                <td width="70" align="right">商品分类：</td>
                <td><select id="classtree" maxlength="50" name="bean.classid" class="easyui-combotree"
                            style="width:250px;height:28px;"
                            data-options="url:'<%=path %>/products/ProductClassPage@loadClassTree2.page'"></select>
                </td>


                <td width="70" align="right">商品编码：</td>
                <td><w:text bind="bean.code" style="width:200px;height:22px;" onchange="value=(value.match(/\d+/g)||['']).join(',')"/></td>
                <td>
                    &nbsp;<a href="javascript:;" class="easyui-linkbutton" iconCls="icon_search"
                             onclick="query1()">查询</a>
                    &nbsp;<a href="javascript:;" class="easyui-linkbutton" iconCls="icon_search"
                             onclick="resetform()">重置</a>
                    &nbsp;<a href="javascript:;" class="easyui-linkbutton" iconCls="icon_search" onclick="inp(this);"
                             id="see">查看已添加商品</a>
                </td>
            </tr>
        </table>
    </div>
</form>

<div title="部分商品" style="border: 1px solid #DDDDDD;">
    <script>
        window.productItems = {};
        window.productItemsTo = {};
        $(function () {
            <w:switch>
            <w:case bind="#productitems_to !=null">
            <w:iterate id="items_pro" bind="#productitems_to" indexId="index">

            var tempProductItem<w:write bind="#index"/> = {};
            var tempProductItemTo<w:write bind="#index"/> = {};
            //获取商品属性
            tempProductItemTo<w:write bind="#index"/>.showlistidto = "<w:write bind="#items_pro.id"/>";
            tempProductItem<w:write bind="#index"/>.showlistid = "<w:write bind="#items_pro.id"/>";
            tempProductItem<w:write bind="#index"/>.showlistname = "<w:write bind="#items_pro.pname"/>";
            tempProductItem<w:write bind="#index"/>.price = "<w:write bind="#items_pro.price"/>";
            tempProductItem<w:write bind="#index"/>.showlistcode = "<w:write bind="#items_pro.code"/>";
            tempProductItem<w:write bind="#index"/>.showlistB_chanjia = "<w:write bind="#items_pro.B_chanjia"/>";
            tempProductItem<w:write bind="#index"/>.showlistB_guige = "<w:write bind="#items_pro.B_guige"/>";
            tempProductItem<w:write bind="#index"/>.showlistclassname = "<w:write bind="#items_pro.classname"/>";
            tempProductItem<w:write bind="#index"/>.showlistproductamount = "<w:write bind="#items_pro.productamount"/>";
            tempProductItem<w:write bind="#index"/>.showlisttypes = "<w:write bind="#items_pro.moneyofftype"/>";
            productItems["key" + tempProductItem<w:write bind="#index"/>.showlistid] = tempProductItem<w:write bind="#index"/>;
            productItemsTo["key" + tempProductItemTo<w:write bind="#index"/>.showlistidto] = tempProductItemTo<w:write bind="#index"/>;
            </w:iterate>
            </w:case>
            <w:case bind="#singleProducitem != null">

            var tempProductItem = {};
            var tempProductItemTo = {};
            //获取商品属性
            tempProductItemTo.showlistidto = "<w:write bind="#singleProducitem.id"/>";
            tempProductItem.showlistid = "<w:write bind="#singleProducitem.id"/>";
            tempProductItem.price = "<w:write bind="#singleProducitem.price"/>";
            tempProductItem.showlistname = "<w:write bind="#singleProducitem.pname"/>";
            tempProductItem.showlistcode = "<w:write bind="#singleProducitem.code"/>";
            tempProductItem.showlistB_chanjia = "<w:write bind="#singleProducitem.B_chanjia"/>";
            tempProductItem.showlistB_guige = "<w:write bind="#singleProducitem.B_guige"/>";
            tempProductItem.showlistclassname = "<w:write bind="#singleProducitem.classname"/>";
            tempProductItem.showlistproductamount = "<w:write bind="#singleProducitem.productamount"/>";
            tempProductItem.showlisttypes = "<w:write bind="#singleProducitem.moneyofftype"/>";
            productItems["key" + tempProductItem.showlistid] = tempProductItem;
            productItemsTo["key" + tempProductItemTo.showlistidto] = tempProductItemTo;
            </w:case>
            </w:switch>
        });

    </script>

    <div class="card_body" style="padding: 20px 19px">
        <div id="chooseShowListPanel" class="easyui-panel" border="false" data-options="doSize:false,href:''">

        </div>
    </div>
</div>

<div style="width: 100%;height: 100px;"></div>
<script>
    function query1() {
        $w.execForm({form: $('#giftform'), target: $('#chooseShowListPanel'), pageNum: 1})
    }
    function resetform() {
        $(".ui-toolBar input").val("");
    }
</script>
<script>
    $(function () {
        $("a.panel-tool-close").unbind("click");
        $("a.panel-tool-close").click(function (e) {
            if (window.confirm("确认取消编辑满赠促销活动?")) {
                window.location.reload();
            }
        });
        var pro_class_value = $("[name='product_type_val']").val();
        if (pro_class_value ==3 || pro_class_value == 0) {
            $("#chooseShowListPanel").hide();
        }

        if(pro_class_value == 1 || pro_class_value == "") {
            $("#bf").prop("checked",true);
        }

        $("#pro_class_set label input").each(function () {
            var pro_txt = $(this).attr("value");
            if( pro_class_value == pro_txt){
                $(this).prop("checked",true);
            }
        })
    })
    function hotquerypro(){
        var giftName = $("#giftLike").val();
        $.ajax({
            url: ctx + "/marketing/FullGiftsPromotionPage@chooseGifts.page?bean.giftName=" + giftName,
            type: "get",
            dataType: "json",
            success: function (ret) {
                $("#rows").val(ret.rows);
                rows = 1;
                $("#shang").hide();
                var g = "";
                var gifts = ret.gifts;
                if(gifts.length < 10) {
                    $("#xia").hide();
                }
                for(var i =0; i< gifts.length;i++){
                    g+="<tr><input type='hidden' name='giftlistid' value='"+ gifts[i].id + "'>" +
                        "<td onclick='chooseGift(this)'>" +gifts[i].productname + "</td><td>" + gifts[i].productcode + "</td></tr>";
                }
                $("#giftList").html(g);
            }
        })
    }
    var rows = 1;
    function shang(){
        var giftName = $("#giftLike").val();
        if (giftName == null) {
            giftName = "";
        }
        if(rows <= 1) {
            return false;
        }
        rows--;
        $.ajax({
            url: ctx + "/marketing/FullGiftsPromotionPage@chooseGifts.page",
            data:{"bean.giftName":giftName,
                "rows":rows
            },
            type: "get",
            dataType: "json",
            success: function (ret) {
                var g = "";
                removeTr();
                var gifts = ret.gifts;
                if(rows == 1) {
                    $("#shang").hide();
                }
                $("#xia").show();
                for(var i =0; i< gifts.length;i++){
                    g+="<tr><input type='hidden' name='giftlistid' value='"+ gifts[i].id + "'>" +
                        "<td onclick='chooseGift(this)'>" +gifts[i].productname + "</td><td>" + gifts[i].productcode + "</td></tr>";
                }
                $("#giftList").html(g);
            }
        })
    }
    function xia(){
        var giftName = $("#giftLike").val();
        if (giftName == null) {
            giftName = "";
        }
        rows++;
        $.ajax({
            url: ctx + "/marketing/FullGiftsPromotionPage@chooseGifts.page",
            data:{"bean.giftName":giftName,
                "rows":rows
            },
            type: "get",
            dataType: "json",
            success: function (ret) {
                var g = "";
                removeTr();
                var gifts = ret.gifts;
                if(gifts.length < 10) {
                    $("#xia").hide();
                }
                $("#shang").show();
                for(var i =0; i< gifts.length;i++){
                    g+="<tr><input type='hidden' name='giftlistid' value='"+ gifts[i].id + "'>" +
                        "<td onclick='chooseGift(this)'>" +gifts[i].productname + "</td><td>" + gifts[i].productcode + "</td></tr>";
                }
                $("#giftList").html(g);
            }
        })
    }
    function removeTr() {
        var tbody = document.getElementById("giftList");
        while(tbody.hasChildNodes()) {
            tbody.removeChild(tbody.firstChild);
        }
    }

    function resetform() {
        $(".ui-toolBar input").val("");
    }
    $("#tab tr:odd").find("td").addClass("tr_odd");
    $("#tab tr:even").find("td").addClass("tr_even");
    $("#tab tr").mouseover(function(){
        $(this).find("td").addClass("mouse_color");
    });
    $("#tab tr").mouseout(function(){
        $(this).find("td").removeClass("mouse_color");
    });
    function inputcheck(obj) {
        obj.value=obj.value.trim().replace(/[^0-9|\.]/g,'');
        obj.value=obj.value.replace(/^\./,'0.');
        obj.value=obj.value.replace(/\.$/,'');
        if(obj.value.indexOf('.')>0 && obj.value.indexOf('.')!=(obj.value.length-1))
        {obj.value=obj.value.substring(0,obj.value.indexOf('.')+1)
            +obj.value.substr(obj.value.indexOf('.')+1,2);
        };
        obj.value=obj.value.replace(/\./g,'_').replace('_','.').replace(/_/g,'');
    }
    function inputcheck2(obj) {
        obj.value=obj.value.trim().replace(/[^0-9]/g,'');
    }
</script>
<script>
    /*点击弹出*/
    var orient;
    function chooseGift(obj) {
        var text = obj.innerHTML;
        var input = obj.parentNode.firstChild.value;
        $("[orient='"+orient+"']").val(text);
        $("[orient='"+orient+"']").attr("product_id",input);
        $("#producttab").hide();
    }
    function fullgifts(obj) {
        /*var objPosition = $(obj).offset();
         $("#producttab").css({
         top: objPosition.top + $(obj).height(),
         left: objPosition.left
         });*/
        $.ajax({
            url: ctx + "/marketing/FullGiftsPromotionPage@chooseGifts.page",
            type: "get",
            dataType: "json",
            success: function (ret) {
                orient = uuid(8,16);
                $(obj).attr("orient",orient);
//                var objPosition = $(obj).offset();
//                $("#producttab").css({
//                    top: objPosition.top + $(obj).height(),
//                    left: objPosition.left
//                })
                var objPosition = $(obj).position().top;
                var objPosition_l = $(obj).position().left;
                $("#producttab").css({
                    top: objPosition + $(obj).height()+5,
                    left: objPosition_l+1
                });
                removeTr();
                var g = "";
                var gifts = ret.gifts;
                for(var i =0; i< gifts.length;i++){
                    g+="<tr><input type='hidden' id='giftlistid' value='"+ gifts[i].id + "'>" +
                        "<td onclick='chooseGift(this)'>" +gifts[i].productname + "</td><td>" + gifts[i].productcode + "</td></tr>";
                }
                $("#giftList").append(g);
                $("#producttab").show();

            }
        })
    }
    function uuid(len, radix) {
        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
        var uuid = [], i;
        radix = radix || chars.length;

        if (len) {
            // Compact form
            for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
        } else {
            // rfc4122, version 4 form
            var r;

            // rfc4122 requires these characters
            uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
            uuid[14] = '4';

            // Fill in random data.  At i==19 set the high bits of clock sequence as
            // per rfc4122, sec. 4.1.5
            for (i = 0; i < 36; i++) {
                if (!uuid[i]) {
                    r = 0 | Math.random()*16;
                    uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                }
            }
        }

        return uuid.join('');
    }
    function selectGift(val) {
        $("[orient='"+orient+"']").val(val);
        $("#producttab").hide();
    }
    $(".close").click(function () {
        $("#producttab").hide();
    })

    /*点击完成按钮验证必填项*/
    $(function () {
        /*当前表单调用validate方法，实现表单验证功能*/
        $("#giftform").validate({
            debug: true, /*调试模式，验证通过也不跳转到目标页面，如要提交跳转修改成false*/
            rules: {
                /*配置验证规则*/
                platform: {
                    required: true/*必填。如果验证方法不需要参数，则配置为true*/
                },
                starttime: {
                 required: true
                 },
                 endtime: {
                 required: true
                 },
                 name: {
                 required: true
                 },
                 bean2: {
                 required: true
                 },
                money_tag:{
                    required:true
                },
                fulldelivery:{
                    required:true
                },
                productinput:{
                    required:true
                },
                buysend:{
                    required:true
                },
                productunit:{
                    required:true
                },
                productgive:{
                    required:true
                },
            },
            messages: {
                platform: {
                    required: "推广平台不能为空，必选一项!"
                },
                starttime: {
                 required: "活动开始时间不能为空"
                 },
                 endtime: {
                 required: "活动结束时间不能为空"
                 },
                 name: {
                 required: "活动标题不能为空"
                 },
                 bean2: {
                 required: "活动规则不能为空，必选一项!"
                 },
                money_tag:{
                    required:"满多少元不能为空"
                },
                fulldelivery:{
                    required:"送多少件不能为空"
                },
                productinput:{
                    required:"赠品不能为空"
                },
                buysend:{
                    required:"买多少件不能为空"
                },
                productunit:{
                    required:"送多少件不能为空"
                },
                productgive:{
                    required:"赠品不能为空"
                },
            },
            /* 重写错误显示消息方法,以吐司方式弹出错误消息 */
            /*获取单项必填项消息*/
            showErrors: function (errorMap, errorList) {
                var msg = "";
                $.each(errorList, function (i, v) {
                    if (i == 0)//每次只弹出一个提示
                    {
                        msg += (v.message + "\r\n");
                    }
                });
                if (msg != "")
//                    toastr.warning(msg) || toastr.success(msg)
                    $("#errormsg").html(msg).fadeIn(300).delay(2000).fadeOut(300);
            },
            /* 失去焦点时不验证 */
            onfocusout: false,
            submitHandler: function (form) {
                /*执行提交的函数*/
                pedit_prodoctupdate();
            }

        });
    });
    $(function () {
        var start = $("[name='bean.start_time']").val();
        $("[name='starttime']").val(start)
        var end = $("[name='bean.end_time']").val();
        $("[name='endtime']").val(end);
        chooseShowList();
    })

    //删除控销用户
    function delcontroluser(obj) {
        $(obj).parent().parent().remove();
    }
    function chooseShowList() {
        $w.execUrl(ctx + "/marketing/FullGiftsPromotionPage@chooseMoneyList.page", {}, $('#chooseShowListPanel'));
    }
    //添加控销
    function addControlsales() {
        window.parent.$w.openDialog({
            url: ctx + '/products/ProductPage@addControlsalesShow.page',
            title: "活动控销",
            w: 600,
            h: 400,
            afterClose: function (ret) {
                if (ret && ret.list.length > 0) {
                    var txt = "";
                    var combox = $("#controlsales").get(0);
                    for (var i = 0; i < ret.list.length; i++) {
                        if (ret.type == "1") txt = "客户分组：" + ret.list[i].text;
                        else if (ret.type == "2") txt = "价格等级：" + ret.list[i].text;
                        else if (ret.type == "3") txt = "区域控销：" + ret.list[i].text;
                        val = "{'type':'" + ret.type + "','val':'" + ret.list[i].val + "','text':'" + txt + "'}";
                        combox.options[combox.options.length] = new Option(txt, val);
                    }
                }
            }
        })
    }
    function delControlsales() {
        var combox = $("#controlsales").get(0);
        if (combox.options.length > 0) {
            for (var i = 0; i < combox.options.length; i++) {
                var option = combox.options[i];
                if (option.selected) {
                    combox.options[i] = null;
                    i--;
                }
            }
        }
    }
    /*规则限制单选框根据选中的值显示不同*/
    $(function () {
        var aa = "<w:write bind="bean.items"/>";
        if(aa.length > 0) {
            $("#me").prop("checked",true);
        }else {
            $("#ml").prop("checked",true);
        }
        showCont();
        $("input[name=bean2]").click(function () {
            showCont();
        });
    });
    function showCont() {
        switch ($("input[name=bean2]:checked").attr("id")) {
            case "me":
                $("#buy").hide();
                $("#full").show();
                break;
            case "ml":
                $("#full").hide();
                $("#buy").show();
                break;
            default:
                break;
        }
    }

    /*点击满额送*/
    function full_left_add(obj) {
        var h = "";
        h += "<div class='full_content'>"
        h += "<p class='_full' style='margin-left: 170px;'>"
        h += "<a style='padding: 0 5px;' href='javascript:;' class='newbtna' onclick='fulldelone(this)'>[-]</a>"
        h += "满<input name='money_tag' onblur='inputcheck(this);' maxlength='7' value='' data-options='required:true' style='width:100px;margin: 0 4px;'><i style='margin-right: 4px;margin-left:4px;font-style: normal;'>元</i>"
        h += "送<input name='fulldelivery' onblur='inputcheck2(this);' maxlength='7' value='' data-options='required:true' style='width:100px;margin: 0 6px;'><i style='font-style: normal;margin-left: 3px;margin-right: 2px;'>件</i>"
        h += "<input type='text' name='productinput' class='productinput' onclick='fullgifts(this);' style='width: 150px;margin-left: 2px;margin-right: 4px;' readonly>"
        h += "<a href='#' style=' color: red;text-decoration: none;' onclick='full_left_new_add(this)'>[+]</a>"
        h += "</p>"
        h += "</div>"
        $(obj).parents("div #full").append(h);
    }
    function full_right_add(obj) {
        var h = "";
        h += "<p class='full_list' style='margin-left: 340px;'>"
        h += "<i style='font-style: normal;margin-left: 5px;'>送</i><input name='fulldelivery' onblur='inputcheck2(this);' maxlength='7' value='' data-options='required:true' style='width:100px;margin: 0 5px;'><i style='font-style: normal;margin-left: 4px;margin-right: -1px;'>件</i>"
        h += "<input type='text' name='productinput' class='productinput' onclick='fullgifts(this);' style='width: 150px;margin: 0 5px;' readonly>"
        h += "<a href='javascript:;' class='newbtna' onclick='fulldeltwo(this)'>[-]</a>"
        h += "</p>"
        $(obj).parents("div .full_content").append(h);
    }
    function full_left_new_add(obj) {
        var h = "";
        h += "<p class='full_list' style='margin-left: 340px;'>"
        h += "<i style='font-style: normal;margin-left: 5px;'>送</i><input name='fulldelivery' onblur='inputcheck2(this);' maxlength='7' value='' data-options='required:true' style='width:100px;margin: 0 5px;'><i style='font-style: normal;margin-left: 4px;margin-right: -1px;'>件</i>"
        h += "<input type='text' style='width: 150px;margin: 0 5px;' onclick='fullgifts(this);' name='productinput' class='productinput' readonly>"
        h += "<a href='javascript:;' class='newbtna' onclick='fulldeltwo(this)'>[-]</a>"
        h += "</p>"
        $(obj).parents("div .full_content").append(h);
    }
    /*点击满数量送*/
    function buy_left_add(obj) {
        var h = "";
        h += "<div class='buy_content'>"
        h += "<p class='_buy' style='margin-left: 170px;'>"
        h += "<a style='padding: 0 5px;' href='javascript:;' class='newbtna' onclick='buydelone(this)'>[-]</a>"
        h += "买<input name='buysend' onblur='inputcheck(this);' maxlength='7' value='' data-options='required:true' style='width:100px;margin: 0 5px;'><i style='margin-left:-1px;font-style: normal;'>件</i>"
        h += "<i style='font-style: normal;margin-left: 4px;margin-right: 2px;'>送</i><input name='productunit' onblur='inputcheck2(this);' maxlength='7' value='' data-options='required:true' style='width:100px;margin: 0 3px;'><i style='font-style: normal;margin-left: 2px;margin-right: 3px;'>件</i>"
        h += "<input type='text' style='width: 150px;margin-right: 5px;' name='productgive' class='productgive' onclick='fullgifts(this)' readonly>"
        h += "<a href='#' style=' color: red;text-decoration: none;' onclick='buy_left_new_add(this)'>[+]</a>"
        h += "</p>"
        h += "</div>"
        $(obj).parents("div #buy").append(h);
    }
    function buy_right_add(obj) {
        var h = "";
        h += "<p class='buy_list' style='margin-left: 340px;'>"
        h += "<i style='font-style: normal;margin-left: 1px;'>送</i><input name='productunit' onblur='inputcheck2(this);' maxlength='7' value='' data-options='required:true' style='width:100px;margin: 0 5px;'><i style='font-style: normal;'>件</i>"
        h += "<input type='text' style='width: 150px;margin-left: 4px;margin-right: 5px;' name='productgive' class='productgive' onclick='fullgifts(this)' readonly>"
        h += "<a href='javascript:;' class='newbtna' onclick='buydeltwo(this)'>[-]</a>"
        h += "</p>"
        $(obj).parents("div .buy_content").append(h);
    }
    function buy_left_new_add(obj) {
        var h = "";
        h += "<p class='buy_list' style='margin-left: 340px;'>"
        h += "<i style='font-style: normal;margin-left: 1px;'>送</i><input name='productunit' onblur='inputcheck2(this);' maxlength='7' value='' data-options='required:true' style='width:100px;margin: 0 5px;'><i style='font-style: normal;'>件</i>"
        h += "<input type='text' style='width: 150px;margin-left: 4px;margin-right: 5px;' name='productgive' class='productgive' onclick='fullgifts(this)' readonly>"
        h += "<a href='javascript:;' class='newbtna' onclick='buydeltwo(this)'>[-]</a>"
        h += "</p>"
        $(obj).parents("div .buy_content").append(h);
    }
    /*点击减号删除*/
    function fulldelone(obj) {
        $(obj).parents(".full_content").remove();
    }
    function fulldeltwo(obj) {
        $(obj).parent().remove();
    }
    function buydelone(obj) {
        $(obj).parents(".buy_content").remove();
    }
    function buydeltwo(obj) {
        $(obj).parent().remove();
    }
    /*参与方式单选框根据选中的值显示不同*/
    $(function () {
        showactivity();
        $("input[name=bean4]").click(function () {
            showactivity();
        });
    });
    function showactivity() {
        switch ($("input[name=bean4]:checked").attr("id")) {
            case "qc":
                $("#puctfl").hide();
                $("#puctname").hide();
                $("#puctbar").hide();
                $("#puctbtn").hide();
                $("#seetab").hide();
                $("#seestab").hide();
                $("#selectpro").hide();
                break;
            case "bf":
                $("#puctfl").hide();
                $("#puctname").show();
                $("#puctbar").show();
                $("#puctbtn").show();
                $("#seetab").show();
                $("#selectpro").show();
                $("#chooseShowListPanel").show();
                break;
            case "zd":
                $("#puctfl").show();
                $("#puctname").hide();
                $("#puctbar").hide();
                $("#puctbtn").hide();
                $("#seetab").hide();
                $("#seestab").hide();
                $("#selectpro").hide();
                break;
            default:
                break;
        }
    }

    //实现日期选择联动
    var start = {
        format: 'YYYY-MM-DD hh:mm:ss',//日期格式
        minDate: $.nowDate({DD: 0}), //设定最小日期为当前日期
        maxDate: '2099-06-16 23:59:59', //最大日期
        festival: true,//是否显示节日
        isClaer: true,//是否显示清空
        isinitVal: false,//是否初始化时间
        zIndex: 300000,//层级高度
        choosefun: function (elem, datas) {
            end.minDate = datas; //开始日选好后，重置结束日的最小日期
            endDates();
        },//选中日期回调
        okfun: function (elem, datas) {
            //alert(datas)
        }//点击确定回调
    };
    var end = {
        format: 'YYYY-MM-DD hh:mm:ss',//日期格式
        minDate: $.nowDate({DD: 0}), //设定最小日期为当前日期
        maxDate: '2099-06-16 23:59:59', //最大日期
        festival: true,//是否显示节日
        isClaer: true,//是否显示清空
        isinitVal: false,//是否初始化时间
        zIndex: 300000,//层级高度
        choosefun: function (elem, datas) {
            start.maxDate = datas; //将结束日的初始值设定为开始日的最大日期
        }
    };
    //日期联动
    function endDates() {
        end.trigger = false; //结束日期的事件改成false
        $("#giftsEditinpend").jeDate(end);
    }
    $("#giftsEditInpstart").jeDate(start);
    $("#giftsEditinpend").jeDate(end);

    function pedit_prodoctupdate() {
//        $.messager.progress();
        pedit_saveProduct();
    }

    var pedit_saveing = false;
    function pedit_saveProduct() {
        /*if ($("input[name='bean4']:checked").val() == 3) {
            if ($("[name='bean.classid1']").val() == "" || $("[name='bean.classid1']").val() == "null") {
                $("#errormsg").html("请选择要添加的类目").show(300).delay(3000).hide(300);
                return false;
            }
        }*/
        if (!pedit_saveing) {
            pedit_saveing = true;//防止重复保存
            var data = productdata();
            if(!data) {
                pedit_saveing = false;
                return false;
            }
            $w.doUrl(ctx + "/marketing/FullGiftsPromotionPage@update.page", data, function (ret) {
                $.messager.progress('close');
                if (ret.state == 'ok') {
                    window.parent.$w.correctMsg("保存商品成功");
                    $w.closeCurrWin("ok");
                } else if (ret.state == 'no') {
                    pedit_saveing = false;
                    window.parent.$w.alertMsg("编辑失败,商品已参加活动");
                } else {
                    pedit_saveing = false;
                    window.parent.$w.alertMsg(ret.state);
                }
            })
        }
    }
    //组合数据
    function productdata() {
        var win = $w.currWin();
        var data = {
            "bean.promotid": $("[name='promotionid']").val(),
            "bean.start_time": $("#giftsEditInpstart").val(),
            "bean.name": $("[name='name']").val(),
            "bean.end_time": $("#giftsEditinpend").val(),
            "bean.description": $("[name='description']").val(),
            "bean.classid": $("[name='bean.classid1']").val(),
            "bean.time": $("[name='time']").val(),
            "bean.classname": $("[name='classname']").val(),
            "bean.sort_value": $("[name='sort_value']").val(),
            "bean.district_description": $("[name='district_description']").val(),
        };
        data["bean.platform"] = $("input[name='platform']:checked").val();
//            data["bean.count_down"] = $("input[name='count_down']:checked").val();
//            data["bean.product_val"] = $("input[name='primaryKey']:checked").val();

        data["bean.product_type"] = $("input[name='bean4']:checked").val();

//          var check = $("input[name='bean4']")
//        for (int i=0;i<=check.length;i++) {
//            checkbox1.push(check[k])
//        }
       /* if ($("input[name='bean4']:checked").val() == 2) {
            if (productids.length <= 0) {
                $("#errormsg").html("请选择要添加活动的商品").show(300).delay(3000).hide(300);
                return false;
            }
        }*/
        var productid_items = [];

        if (productItemsTo) {
            for (var key in productItemsTo) {
                var val = productItemsTo[key];
                console.log(val);
                if (val.showlistidto) {
                    productid_items.push(val.showlistidto);
                }
            }
        }

        data["bean.product_val"] = JSON.stringify(productid_items);
        var controlsales = "";//控销数据
        var combox = $("#controlsales").get(0);
        for (var i = 0; i < combox.options.length; i++) {
            if (controlsales != "") controlsales += ",";
            controlsales += combox.options[i].value;
        }
        data["bean.controlsales"] = "[" + controlsales + "]";
        var controlusers = "";//控销用户
        $("[name='controluserid']").each(function () {
            controlusers += this.value + ",";
        })
        data["bean.controlusers"] = controlusers

        var items = [];
        var giftType = $("[name='bean2']:checked").val();
        var resultFlag = true;

        if (giftType == '0') {
            $(".full_content").each(function () {
                var item = {};
                item["min_money"] = $(this).find("[name='money_tag']").val();
                var events = [];
                var event = {};
                event["unit"] = $(this).find("[name='fulldelivery']").val();
                event["productid"] = $(this).find("[name='productinput']").attr("product_id");
                if(event["unit"] == "" || !event["productid"] || item["min_money"] == "") {
                    $("#errormsg").html("请填写完整的活动规则").show(300).delay(3000).hide(300);
                    resultFlag = false;
                    return false;
                }
                events.push(event);
                $(this).find(".full_list").each(function () {
                    var event = {};
                    event["unit"] = $(this).find("[name='fulldelivery']").val();
                    event["productid"] = $(this).find("[name='productinput']").attr("product_id");
                    if(event["unit"] == "" || !event["productid"]) {
                        $("#errormsg").html("请填写完整的活动规则").show(300).delay(3000).hide(300);
                        resultFlag = false;
                        return false;
                    }
                    events.push(event);
                })
                item["gifts"] = events;
                items.push(item);
            });

        } else if (giftType == '1') {
            $(".buy_content").each(function () {
                var item = {};
                item["min_number"] = $(this).find("[name='buysend']").val();
                var events = [];
                var event = {};
                event["unit"] = $(this).find("[name='productunit']").val();
                event["productid"] = $(this).find("[name='productgive']").attr("product_id");
                if(event["unit"] == "" || !event["productid"] || item["min_number"] == "") {
                    $("#errormsg").html("请填写完整的活动规则").show(300).delay(3000).hide(300);
                    resultFlag = false;
                    return false;
                }
                events.push(event);
                $(this).find(".buy_list").each(function () {
                    var event = {};
                    event["unit"] = $(this).find("[name='productunit']").val();
                    event["productid"] = $(this).find("[name='productgive']").attr("product_id");
                    if(event["unit"] == "" || !event["productid"]) {
                        $("#errormsg").html("请填写完整的活动规则").show(300).delay(3000).hide(300);
                        resultFlag = false;
                        return false;
                    }
                    events.push(event);
                })
                item["gifts"] = events;
                items.push(item);
            });
        }
        data["bean.gift"] = JSON.stringify(items);
        return resultFlag ? data : resultFlag ;
    }
</script>